using System.Collections;
using UnityEngine;

public class MatchTestPlayer : MonoBehaviour
{
	private FakeRoom room;

	private PhotonClone photonClone;

	private MultiplayerConnectMain.PlayerDescription desc;

	public float startTime;

	public float connectTime;

	public float connectDuration;

	protected string myName
	{
		get
		{
			return desc.name;
		}
	}

	public bool isConnected
	{
		get
		{
			return room != null && room.isInMatch;
		}
	}

	public void Init(MultiplayerConnectMain.PlayerDescription desc, PhotonClone photonClone)
	{
		this.photonClone = photonClone;
		this.desc = desc;
		photonClone.SendToLobby(this);
		StartCoroutine(TryToConnect2());
		startTime = Time.timeSinceLevelLoad;
	}

	public void SetConnected(FakeRoom room)
	{
		this.room = room;
		if (room != null && room.isInMatch)
		{
			connectTime = Time.timeSinceLevelLoad;
			connectDuration = connectTime - startTime;
		}
	}

	private IEnumerator TryToConnect2()
	{
		int connectionTryIndex = 0;
		int currentConnectionRepeats = 0;
		while (true)
		{
			MultiplayerConnectMain.PlayerDescription.ConnectionTry connectionTry = desc.connectionTry[Mathf.Clamp(connectionTryIndex, 0, desc.connectionTry.Count)];
			int numConnectTries = connectionTry.numConnectionTries;
			int tryIndex = 0;
			FloatRange filter = new FloatRange
			{
				min = desc.skillLevel,
				max = desc.skillLevel
			};
			do
			{
				if (tryIndex > 0)
				{
					yield return new WaitForSeconds(connectionTry.timeBetweenConnectTries);
				}
				float difference = Mathf.Lerp(0f, connectionTry.maxSkillLevelDifference, (float)tryIndex / (float)numConnectTries);
				filter.min = desc.skillLevel - difference;
				filter.max = desc.skillLevel + difference;
				yield return photonClone.JoinRandomRoom(this, filter);
				tryIndex++;
			}
			while (tryIndex <= numConnectTries && !isConnected);
			if (!isConnected)
			{
				yield return CreateRoom(desc.skillLevel);
				yield return new WaitForSeconds(connectionTry.waitInRoom.Random());
				if (isConnected)
				{
					break;
				}
				photonClone.RemoveRoom(room);
				room = null;
				currentConnectionRepeats++;
				if (connectionTry.repeatTimes >= 0 && currentConnectionRepeats >= connectionTry.repeatTimes)
				{
					connectionTryIndex++;
					currentConnectionRepeats = 0;
				}
				continue;
			}
			break;
		}
	}

	private Coroutine CreateRoom(float skill)
	{
		FakeRoom fakeRoom = new FakeRoom();
		fakeRoom.c0 = skill;
		fakeRoom.name = myName + "-Room";
		return photonClone.CreateRoom(this, fakeRoom);
	}
}
